// utils/http.js - CapacitorHttp 封装请求方法
import { CapacitorHttp } from '@capacitor/core';

// 检查 token 是否过期
function isTokenExpired() {
  try {
    const tokenStr = localStorage.getItem('oauth_token');
    if (!tokenStr) {
      return true;
    }
    
    const tokenData = JSON.parse(tokenStr);
    const currentTime = Math.floor(Date.now() / 1000);
    const expireTime = tokenData.issue_date + tokenData.expires_in;
    
    // 提前30秒刷新token，避免边界情况
    return currentTime >= (expireTime - 30);
  } catch (error) {
    console.error('检查 token 过期状态失败:', error);
    return true;
  }
}

// 刷新 Token
async function refreshToken() {
  try {
    const tokenStr = localStorage.getItem('oauth_token');
    if (!tokenStr) {
      throw new Error('没有找到 refresh_token');
    }
    
    const tokenData = JSON.parse(tokenStr);
    if (!tokenData.refresh_token) {
      throw new Error('refresh_token 不存在');
    }


    const response = await CapacitorHttp.request({
      url: `/forumsapp/refreshToken.php?refresh_token=${tokenData.refresh_token}`,
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (response.status === 200 && response.data) {
      // 解析响应数据
      let newTokenData;
      if (typeof response.data === 'string') {
        newTokenData = JSON.parse(response.data);
      } else {
        newTokenData = response.data;
      }
      
      // 更新本地存储的token
      const updatedToken = {
        access_token: newTokenData.access_token || tokenData.access_token,
        refresh_token: newTokenData.refresh_token || tokenData.refresh_token,
        token_type: newTokenData.token_type || tokenData.token_type,
        expires_in: parseInt(newTokenData.expires_in) || tokenData.expires_in,
        issue_date: newTokenData.issue_date ? parseInt(newTokenData.issue_date) : Math.floor(Date.now() / 1000)
      };
      
      localStorage.setItem('oauth_token', JSON.stringify(updatedToken));      
      return updatedToken;
    } else {
      throw new Error(`刷新token失败: ${response.status}`);
    }
  } catch (error) {
    console.error('刷新 token 失败:', error);
    // 刷新失败时清除token，强制重新登录
    localStorage.removeItem('oauth_token');
    throw error;
  }
}

// 获取有效的Token
export async function getValidToken() {
  if (isTokenExpired()) {
    try {
      return await refreshToken();
    } catch (error) {
      console.error('刷新token失败:', error);
      return null;
    }
  }
  
  try {
    const tokenStr = localStorage.getItem('oauth_token');
    return JSON.parse(tokenStr);
  } catch (error) {
    console.error('获取 token 失败:', error);
    return null;
  }
}

// 封装的 CapacitorHttp 请求方法
export async function httpRequest(options = {}) {
  try {
    // 获取有效token
    const token = await getValidToken();
    
    if (!token) {
      throw new Error('无法获取有效的访问令牌，请重新登录');
    }
    // 构建请求头
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token.access_token}`,
      ...options.headers
    };
    
    // 构建完整的请求选项
    const requestOptions = {
      method: 'GET',
      ...options,
      headers
    };
    if (process.env.PROD) {
        requestOptions.url = process.env.site + requestOptions.url
    }

    // 发送请求
    const response = await CapacitorHttp.request(requestOptions);
    
    // 处理401未授权错误
    if (response.status === 401) {
      // 尝试刷新token并重试
      try {
        const newToken = await refreshToken();
        
        // 更新请求头中的token
        requestOptions.headers['Authorization'] = `Bearer ${newToken.access_token}`;
        
        // 重新发送请求
        const retryResponse = await CapacitorHttp.request(requestOptions);
        return retryResponse;
      } catch (refreshError) {
        console.error('刷新token后重试失败:', refreshError);
        throw new Error('认证失败，请重新登录');
      }
    }
    
    return response;
  } catch (error) {
    console.error('HTTP请求失败:', error);
    throw error;
  }
}

// 便捷的HTTP方法封装
export const http = {
  // GET 请求
  async get(url, options = {}) {
    return httpRequest({
      url,
      method: 'GET',
      ...options
    });
  },
  
  // POST 请求
  async post(url, data = null, options = {}) {
    return httpRequest({
      url,
      method: 'POST',
      data,
      ...options
    });
  },
  
  // PUT 请求
  async put(url, data = null, options = {}) {
    return httpRequest({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },
  
  // DELETE 请求
  async delete(url, options = {}) {
    return httpRequest({
      url,
      method: 'DELETE',
      ...options
    });
  },
  
  // PATCH 请求
  async patch(url, data = null, options = {}) {
    return httpRequest({
      url,
      method: 'PATCH',
      data,
      ...options
    });
  }
};

// 错误处理工具
export function handleApiError(error) {
  if (error.message?.includes('认证失败') || error.message?.includes('请重新登录')) {
    // 跳转到登录页面
    window.location.href = '/login';
    return;
  }
  
  // 其他错误处理
  console.error('API错误:', error);
  
  // 可以在这里添加全局错误提示
  // 例如使用 Toast 或 Modal 显示错误信息
}